<template>
  <!-- 添加商品模块 -->
  <div class="addGoods">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 消息提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- step 步骤条区域 -->
      <el-steps :active="activeIndex" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 添加商品表单区域 -->
      <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRef">
        <!-- tabs 标签页区域 -->
        <el-tabs
          tab-position="left"
          v-model="activeName"
          @tab-click="handleTabClicked"
          :before-leave="handleTabBeforeClicked"
        >
          <!-- 基本信息区域 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 分类级联选择器 -->
              <el-cascader v-model="selectedCate" :options="cateList" :props="cateProps"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" border v-for="(cb, i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 商品图片上传 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="content"></quill-editor>
            <!-- 添加按钮 -->
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 图片预览对话框 -->
      <el-dialog title="图片预览" :visible.sync="dialogPreviewVisible">
        <img :src="imgUrl" class="previewImg" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // tabs 激活name属性值
      activeName: '0',
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: '',
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请填写商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请填写商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请填写商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请填写商品数量', trigger: 'blur' }
        ]
      },
      selectedCate: [],
      cateList: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      manyTableData: [],
      onlyTableData: [],
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      imgUrl: '',
      pics: [],
      dialogPreviewVisible: false,
      content: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$axios.get('categories')
      // 获取分类数据失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败!!!')
      }
      // 获取成功
      this.cateList = res.data
    },
    handleTabBeforeClicked() {
      if (this.activeIndex === 0 && this.selectedCate.length !== 3) {
        this.$message.error('请先选择商品分类！！！')
        return false
      }
    },
    async handleTabClicked() {
      // 获取动态参数
      if (this.activeIndex === 1) {
        const { data: res } = await this.$axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        // 获取参数失败
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数失败')
        }
        this.manyTableData = res.data.map(item => {
          item.attr_vals =
            item.attr_vals === '' ? [] : item.attr_vals.split(',')
          return item
        })
      }
      // 获取静态属性
      if (this.activeIndex === 2) {
        const { data: res } = await this.$axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        // 获取参数失败
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数失败')
        }
        this.onlyTableData = res.data
      }
    },
    handleSuccess(file) {
      // 上传图片失败
      if (file.meta.status !== 200) {
        return this.$message.error('上传图片失败')
      }
      this.$message({
        type: 'success',
        message: '上传图片成功'
      })
      this.pics.push({
        pic: file.data.tmp_path
      })
    },
    handlePreview(file) {
      this.dialogPreviewVisible = true
      this.imgUrl = file.response.data.url
    },
    handleRemove(file) {
      this.pics = this.pics.filter(item => {
        return item.tmp_path !== file.response.data.tmp_path
      })
    },
    addGoods() {
      // 表单预验证
      this.$refs['addGoodsFormRef'].validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整的商品信息！！！')
        }
        // 分类id
        this.addGoodsForm.goods_cat = this.selectedCate.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals.join(',')
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 上传图片临时路径
        this.addGoodsForm.pics = this.pics
        // 商品介绍
        this.addGoodsForm.goods_introduce = this.content

        // 保存商品信息
        const { data: res } = await this.$axios.post('goods', {
          ...this.addGoodsForm
        })

        // 添加商品失败
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败！！！')
        }
        this.$message({
          type: 'success',
          message: res.meta.msg
        })
        this.$router.replace('/goods')
      })
    }
  },
  computed: {
    // 步骤条的索引
    activeIndex() {
      return Number(this.activeName)
    },
    // 分类参数
    cateId() {
      if (this.selectedCate.length === 3) {
        return this.selectedCate[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-tabs {
  min-height: 600px !important;
}
.el-cascader {
  width: 100%;
}
.el-checkbox {
  margin: 0 5px;
}
.previewImg {
  width: 100%;
}
.el-button {
  margin-top: 15px;
}
</style>
<style lang="less">
.addGoods {
  .el-form-item__label {
    float: none !important;
  }
  .ql-container {
    height: 300px;
  }
}
</style>
